import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {CookieService} from 'ngx-cookie-service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'aaa';
  authenticated = false;
  credentials = {username:"xixi",password:"123"};
  order = '0';
  constructor(private http: HttpClient,private cookieService: CookieService){
      // 基于session的SSO
      // this.http.get('me').subscribe(data => {
      // 基于token的SSO
    this.http.get('api/user/me').subscribe(data => {
        if(data){
          this.authenticated = true;
        }
        if(!this.authenticated){
          window.location.href = 'http://auth.imooc.com:9090/oauth/authorize?' +
            'client_id=admin&' +
            'redirect_uri=http://admin.imooc.com:9999/oauth/callback&'+
            'response_type=code&' +
            'state=abc';
        }
      });
  }

  getOrder() {
    this.http.get('api/order/orders/1').subscribe(data => {
      // alert(data);
      this.order = data.toString();

      // console.log('订单号为： ' + this.order);
    }, () => {
      alert('get order fail');
    });
  }

  logout(){
    this.cookieService.delete('imooc_access_token','/','imooc.com');
    this.cookieService.delete('imooc_refresh_token','/','imooc.com');
    // 1.将客户端应用的session失效掉
    this.http.post('logout',this.credentials).subscribe(()=>{
      // 2.将认证服务器的session失效，/logout 是SpringSecurity OAuth默认的退出过滤器
      window.location.href = 'http://auth.imooc.com:9090/logout?redirect_uri=http://admin.imooc.com:9999';
    },()=>{
      alert('logout fail');
    });
  }

  login(){
    this.http.post('login',this.credentials).subscribe(()=>{
      this.authenticated = true;
    },()=>{
      alert('login fail');
    });
  }
}
